<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus,
  Edit,
  Delete,
  Search,
  RefreshRight
} from '@element-plus/icons-vue'
import {
  getCatagoriesList,
  addcategories,
  altercategories,
  deletecategories
} from '@/api/catagory'

// 状态定义
const categories = ref([])
const loading = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formMode = ref('add')
const searchQuery = ref('')
const formRef = ref(null)

// 表单数据
const form = ref({
  name: '',
  type: 1,
  sort: 0,
  status: 1
})

// 表单验证规则
const formRules = {
  name: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  sort: [
    { required: true, message: '请输入排序号', trigger: 'blur' },
    { type: 'number', message: '必须为数字值', trigger: 'blur' }
  ]
}

// 获取分类列表
const fetchCategories = async () => {
  loading.value = true
  try {
    const response = await getCatagoriesList()
    categories.value = response.data
  } catch (error) {
    console.error('Error:', error)
    ElMessage.error('获取分类列表失败')
  } finally {
    loading.value = false
  }
}

// 处理新增
const handleAdd = () => {
  formMode.value = 'add'
  dialogTitle.value = '新增分类'
  form.value = {
    name: '',
    type: 1,
    sort: 0,
    status: 1
  }
  dialogVisible.value = true
}

// 处理编辑
const handleEdit = (row) => {
  formMode.value = 'edit'
  dialogTitle.value = '编辑分类'
  form.value = { ...row }
  dialogVisible.value = true
}

// 处理删除
const handleDelete = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除这个分类吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await deletecategories(id)
    ElMessage.success('删除成功')
    fetchCategories()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('Error:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    loading.value = true

    if (formMode.value === 'add') {
      await addcategories(form.value)
      ElMessage.success('添加成功')
    } else {
      await altercategories(form.value)
      ElMessage.success('更新成功')
    }

    dialogVisible.value = false
    fetchCategories()
  } catch (error) {
    console.error('Error:', error)
    ElMessage.error('提交失败')
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  fetchCategories()
})
</script>

<template>
  <div class="category-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="title-section">
        <h2 class="page-title">分类管理</h2>
        <p class="page-subtitle">管理和组织餐厅的菜品分类</p>
      </div>
      <div class="action-section">
        <el-input
          v-model="searchQuery"
          placeholder="搜索分类..."
          class="search-input"
          :prefix-icon="Search"
          clearable
        />
        <el-button type="primary" @click="handleAdd" class="add-button">
          <el-icon><Plus /></el-icon>新增分类
        </el-button>
        <el-button @click="fetchCategories" class="refresh-button">
          <el-icon><RefreshRight /></el-icon>刷新
        </el-button>
      </div>
    </div>

    <!-- 表格内容区 - 优化后的列宽布局 -->
    <div class="table-container">
      <el-table
        v-loading="loading"
        :data="
          categories.filter(
            (data) =>
              !searchQuery ||
              data.name.toLowerCase().includes(searchQuery.toLowerCase())
          )
        "
        border
        class="category-table"
      >
        <!-- 序号列 - 从1开始计数 -->
        <el-table-column type="index" label="序号" width="100" align="center">
          <template #default="scope">
            <span>{{ scope.$index + 1 }}</span>
          </template>
        </el-table-column>

        <!-- 分类名称列 - 较小固定宽度 -->
        <el-table-column prop="name" label="分类名称" width="331">
          <template #default="{ row }">
            <div class="category-name">
              <span>{{ row.name }}</span>
            </div>
          </template>
        </el-table-column>

        <!-- 排序列 - 固定宽度 -->
        <el-table-column prop="sort" label="排序" width="90" align="center" />

        <!-- 状态列 - 适中宽度 -->
        <el-table-column label="状态" width="300" align="center">
          <template #default="{ row }">
            <el-tag
              :type="row.status === 1 ? 'success' : 'danger'"
              class="status-tag"
            >
              {{ row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>

        <!-- 操作列 - 固定在右侧，适中宽度 -->
        <el-table-column label="操作" width="480" fixed="right" align="center">
          <template #default="{ row }">
            <el-button-group class="operation-buttons">
              <el-button
                type="primary"
                :icon="Edit"
                @click="handleEdit(row)"
                text
              >
                编辑
              </el-button>
              <el-button
                type="danger"
                :icon="Delete"
                @click="handleDelete(row.id)"
                text
              >
                删除
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 弹窗表单 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
      destroy-on-close
      class="category-dialog"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="formRules"
        label-width="100px"
        class="category-form"
      >
        <el-form-item label="分类名称" prop="name">
          <el-input
            v-model="form.name"
            placeholder="请输入分类名称"
            class="form-input"
          />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number
            v-model="form.sort"
            :min="0"
            :max="999"
            class="form-number"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-switch
            v-model="form.status"
            :active-value="1"
            :inactive-value="0"
            inline-prompt
            active-text="启用"
            inactive-text="禁用"
            class="form-switch"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="loading">
            {{ formMode === 'add' ? '创建' : '保存' }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.category-container {
  padding: 24px;
  background-color: #e8f4f8;
  min-height: calc(100vh - 60px);
  background-image: linear-gradient(135deg, #e8f4f8 0%, #d1e8f0 100%);
}

.page-header {
  margin-bottom: 24px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title-section {
  flex: 1;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #1a1a1a;
  margin: 0;
}

.page-subtitle {
  margin-top: 4px;
  color: #666;
  font-size: 14px;
}

.action-section {
  display: flex;
  gap: 12px;
  align-items: center;
}

.search-input {
  width: 240px;
  transition: all 0.3s;
}

.search-input:focus-within {
  width: 280px;
}

.add-button {
  background: linear-gradient(135deg, #1890ff 0%, #096dd9 100%);
  border: none;
  padding: 8px 16px;
}

.add-button:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(24, 144, 255, 0.35);
}

.refresh-button {
  border: 1px solid #d9d9d9;
}

.table-container {
  background: rgba(255, 255, 255, 0.9);
  border-radius: 8px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  padding: 24px;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.category-table {
  width: 100%;
  border-radius: 8px;
  overflow: hidden;
}

.category-name {
  display: flex;
  align-items: center;
  gap: 8px;
}

.status-tag {
  padding: 4px 8px;
  border-radius: 4px;
}

.operation-buttons {
  display: inline-flex;
  gap: 8px;
}

/* 响应式布局优化 */
@media screen and (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: stretch;
    gap: 16px;
  }

  .action-section {
    flex-wrap: wrap;
  }

  .search-input {
    width: 100%;
  }

  .category-table {
    font-size: 14px;
  }
}
</style>
